import { useEffect, useRef, useState } from "react";

function useJieliu(initTime = 5) {
    const timer = useRef(null);

    const [codeTime, setCodeTime] = useState(initTime);

    const [isRuing, setIsRuing] = useState(false);

    const startCodeTime = () => {
        if (!isRuing) {
            setIsRuing(true)
            timer.current = setInterval(() => {
                setCodeTime((pre) => {
                    if (pre < 1) {
                        clearInterval(timer.current);
                        setIsRuing(false);
                        return initTime;
                    }

                    return pre - 1;
                });
            }, 1000);
        }
    };
    useEffect(() => {
        return () => {
            if (timer.current) {
                clearInterval(timer.current);
            }
        };
    }, []);

    return { codeTime, isRuing, startCodeTime };
}

export default useJieliu;

